package online.chazi.bootplus.commons.crypto;

/**
 * 说明：作者很懒，什么都没留下
 * Created by 叉子同学 on 2020-04-13 15:28
 */
public class XorEncoder {
    public static byte[] xorEncode(String key, byte[] data) {
        //将任意长的key转变成长度为256的新key
        byte[] keyBytes = new byte[256];
        for (int i = 0; i < key.getBytes().length; i++) {
            keyBytes[i] = key.getBytes()[i % key.getBytes().length];
        }
        //该byte[]为输出密文
        byte[] encodeBytes = new byte[data.length];
        //在每一轮循环中对key下功夫，比如置换
        int j = 0;
        int k = 0;
        for (int i = 0; i < encodeBytes.length; i++) {
            k = 0xff & k + 1;
            j = 0xff & j + keyBytes[k];
            int m = keyBytes[k];
            keyBytes[k] = keyBytes[j];
            keyBytes[j] = (byte) m;
            int n = 0xff & keyBytes[j] + keyBytes[k];
            encodeBytes[i] = (byte) (data[i] ^ keyBytes[n]);
        }
        return encodeBytes;
    }
}
